<template>
  <t-button theme="primary" v-permission="['system:engineering-stage:stage-extension-apply']" @click="handleOpenDialog('update', { orderId: props.orderId, engineeringId: props.engineeringId, contractId: props.contractId })">
      申请阶段延期
  </t-button>
  <!-- 自定义对话框 -->
  <custom-dialog
    ref="customDialogRef"
    v-slot="{ formData,readonly }"
    :api-map="{ update: engineeringStageExtensionApply }"
    header="编辑节点"
    :width="800"
    :on-before-save-data="handleDialogSaveData"
    :on-before-set-data="handleDialogSetData"
    @request-success="handleDialogRequestSuccess"
  >
  <t-form-item label="节点" name="stageList" label-width="0">
    <div style="width: 100%">
      <t-table
        row-key="id"
        :data="formData.stageList"
        :columns="[
          { colKey: 'stageName', align: 'center',title: '阶段名称', width:120,className:'val' },
          { colKey: 'startTime',align: 'center', title: '开工日期',className:'val' },
          { colKey: 'endTime', align: 'center',title: '完工日期',className:'val' },
          { colKey: 'days', align: 'center',title: '施工天数',className:'val' },
        ]"
        bordered
        size="small"
        stripe
        hover
        >
        <template #startTime="{ row, rowIndex }">
          <t-form-item
            label="开工日期"
            :name="`stageList[${rowIndex}].startTime`"
            :rules="[
              { required: true, message: '请选择开工日期' },
              {
                validator: () => {
                if (!row.endTime) return true;
                return dayjs(row.startTime).isBefore(row.endTime);
                },
                message: '开工日期不能大于完工日期',
              },
              {
          validator: () => {
            if (!props.actualBeginTime) return true;
            return dayjs(row.startTime).isSameOrAfter(props.actualBeginTime);
          },
          message: `开工日期不能早于${dayjs(props.actualBeginTime).format('YYYY-MM-DD')}`,
        },
            ]"
            label-width="0"
            >
              <t-date-picker 
                allow-input
                v-model:value="row.startTime"
                clearable
                placeholder="请选择开工日期"
                value-type="time-stamp"
                style="width: 100%"
                @change="
                  (value) => {
                    if (value) {
                      value = dayjs(value).format('YYYY-MM-DD 23:59:59');

                    }
                    row.startTime = value ? value : undefined;
                  }
                "
              />
            </t-form-item>
          </template>
          <template #endTime="{ row, rowIndex }">
            <t-form-item
              label="完工日期"
              :name="`stageList[${rowIndex}].endTime`"
              :rules="[
                { required: true, message: '请选择完工日期' },
                {
                  validator: () => {
                    if (!row.startTime) return true;
                    return dayjs(row.endTime).isAfter(row.startTime);
                  },
                  message: '完工日期不能小于开工日期',
                },
                {
          validator: () => {
            if (!props.actualEndTime) return true;
            return dayjs(row.endTime).isSameOrBefore(props.actualEndTime);
          },
          message: `完工日期不能晚于${dayjs(props.actualEndTime).format('YYYY-MM-DD')}`,
        },
              ]"
              label-width="0"
            >
              <t-date-picker 
                allow-input
                v-model:value="row.endTime"
                clearable
                placeholder="请选择完工日期"
                value-type="time-stamp"
                style="width: 100%"
                @change="
                  (value) => {
                    if (value) {
                      value = dayjs(value).format('YYYY-MM-DD 23:59:59');

                    }
                    row.endTime = value ? value : undefined;
                  }
                "
              />
            </t-form-item>
          </template>
          <template #days="{ row }">
            {{ calculateDays(row.startTime, row.endTime) }} 
          </template>
      </t-table>
    </div>
  </t-form-item>
  </custom-dialog>
</template>

<script setup lang="ts">
import dayjs from 'dayjs';
import isSameOrAfter from 'dayjs/plugin/isSameOrAfter';
import isSameOrBefore from 'dayjs/plugin/isSameOrBefore';
import { MessagePlugin } from 'tdesign-vue-next';
import { PropType, ref, useTemplateRef } from 'vue';

import { engineeringStageExtensionApply } from '@/api/project/details';
import { getAllSimpleUserlist } from '@/api/system/user';
import CustomDialog from '@/components/custom/dialog/index.vue';


dayjs.extend(isSameOrAfter);
dayjs.extend(isSameOrBefore);
// props
const props = defineProps({
  // 订单ids
  orderId: {
    type: Number,
    required: true,
  },
  engineeringId: {
    type: Number,
    required: true,
  },
  contractId: {
    type: Number,
    required: true,
  },
  stageList: {
    type: Array,
    required: true,
  },
  actualBeginTime: {
    type: String,
    default: ''
  },
  actualEndTime: {
    type: String,
    default: ''
  }
});
// emits
const emits = defineEmits(['requestSuccess']);
// 自定义对话框ref
const customDialogRef = useTemplateRef('customDialogRef');
// 处理打开对话框
const handleOpenDialog = (mode: 'create' | 'read' | 'update', params: Record<string, any>) => {
  customDialogRef.value.open(mode, params);
};
// 处理对话框请求成功
const handleDialogRequestSuccess = (result: Record<string, any>) => {
  emits('requestSuccess', result);
};
// 处理对话框设置数据
const handleDialogSetData = (params: Record<string, any>) => {
  params.stageList = props.stageList
};
// 处理对话框保存数据
const handleDialogSaveData =(params: Record<string, any>)=>{
  if(params.stageList.length===0) {
    MessagePlugin.error('暂无阶段延期');
    return false;
  }
};
// 计算施工天数
const calculateDays = (startTime: any, endTime: any) => {
  if (!startTime || !endTime) return 0;

  const start = dayjs(startTime);
  const end = dayjs(endTime);

  if (start.isAfter(end)) {
    return 0; // 开工时间大于完工时间，返回0天
  }

  return end.diff(start, 'day') + 1; // 包含首尾两天
};
</script>
<style lang="less" scoped>
:deep(.val) {
  line-height: 52px;
}
</style>
